package com.hmdp.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.constants.RedisConstants;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {

        //1.从redis查询(list)
        Long size = stringRedisTemplate.opsForList().size(RedisConstants.CACHE_SHOP_TYPE_KEY);
        //2. redis中是否存在
        if (size != null && size.intValue() != 0) {
            List<String> redisCache = stringRedisTemplate.opsForList().range(RedisConstants.CACHE_SHOP_TYPE_KEY, 0, size);
            //反序列化
            assert redisCache != null;
            List<ShopType> cache = redisCache.stream().map(s -> JSONUtil.toBean(s, ShopType.class)).collect(Collectors.toList());
            return Result.ok(cache);
        }

        //3.查询数据库
        List<ShopType> shopTypeList = this.query().orderByAsc("sort").list();

        //4.不存在
        if (shopTypeList.isEmpty()) {
            return Result.fail("店铺类型不存在！");
        }
        //5.店铺存在 ShopType转json 写入redis(序列化)
        List<String> cacheToRedis = shopTypeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());

        stringRedisTemplate.opsForList().rightPushAll(RedisConstants.CACHE_SHOP_TYPE_KEY, cacheToRedis);
        return Result.ok(shopTypeList);
    }
}
